/**
 * 购物车缓存管理工具
 * 提供统一的购物车数据缓存机制，支持10分钟有效期
 */

const CACHE_DURATION = 10 * 60 * 1000 // 10分钟的毫秒数
const CART_CACHE_KEY = 'user_cart_cache'

export default {
  /**
   * 检查缓存是否有效
   * @param {string} userId 用户ID
   * @returns {boolean} 是否有效
   */
  isCacheValid(userId) {
    const cacheKey = `${CART_CACHE_KEY}_${userId}`
    const cacheData = uni.getStorageSync(cacheKey)
    if (!cacheData || !cacheData.timestamp) {
      return false
    }
    const now = Date.now()
    const cacheTime = cacheData.timestamp
    return (now - cacheTime) < CACHE_DURATION
  },

  /**
   * 获取购物车缓存数据
   * @param {string} userId 用户ID
   * @returns {Array} 购物车数据
   */
  getCartCache(userId) {
    const cacheKey = `${CART_CACHE_KEY}_${userId}`
    const cacheData = uni.getStorageSync(cacheKey)
    return cacheData ? cacheData.data : []
  },

  /**
   * 设置购物车缓存数据
   * @param {string} userId 用户ID
   * @param {Array} data 购物车数据
   */
  setCartCache(userId, data) {
    const cacheKey = `${CART_CACHE_KEY}_${userId}`
    const cacheData = {
      data: data,
      timestamp: Date.now()
    }
    uni.setStorageSync(cacheKey, cacheData)
    console.log(`购物车缓存已保存: ${cacheKey}, 有效期至: ${new Date(Date.now() + CACHE_DURATION).toLocaleString()}`)
  },

  /**
   * 清除购物车缓存
   * @param {string} userId 用户ID
   */
  clearCartCache(userId) {
    const cacheKey = `${CART_CACHE_KEY}_${userId}`
    uni.removeStorageSync(cacheKey)
    console.log(`购物车缓存已清除: ${cacheKey}`)
  },

  /**
   * 清除所有购物车缓存
   */
  clearAllCartCache() {
    try {
      const storageInfo = uni.getStorageInfoSync()
      const keys = storageInfo.keys
      keys.forEach(key => {
        if (key.startsWith(CART_CACHE_KEY)) {
          uni.removeStorageSync(key)
        }
      })
      console.log('所有购物车缓存已清除')
    } catch (error) {
      console.error('清除购物车缓存失败:', error)
    }
  },

  /**
   * 获取缓存状态信息
   * @param {string} userId 用户ID
   * @returns {Object} 缓存状态
   */
  getCacheStatus(userId) {
    const cacheKey = `${CART_CACHE_KEY}_${userId}`
    const cacheData = uni.getStorageSync(cacheKey)
    if (!cacheData) {
      return { exists: false, valid: false }
    }
    
    const now = Date.now()
    const cacheTime = cacheData.timestamp
    const isValid = (now - cacheTime) < CACHE_DURATION
    const remainingTime = isValid ? CACHE_DURATION - (now - cacheTime) : 0
    
    return {
      exists: true,
      valid: isValid,
      cacheTime: new Date(cacheTime).toLocaleString(),
      remainingTime: Math.floor(remainingTime / 1000), // 剩余秒数
      dataCount: cacheData.data ? cacheData.data.length : 0
    }
  },

  /**
   * 添加商品到购物车缓存
   * @param {string} userId 用户ID
   * @param {Object} cartItem 购物车项，必须包含productId和skuId
   */
  addToCartCache(userId, cartItem) {
    let cartData = this.getCartCache(userId)
    
    // 检查是否已存在相同商品和SKU
    const existingIndex = cartData.findIndex(item => 
      item.productId === cartItem.productId && 
      item.skuId === cartItem.skuId
    )
    
    if (existingIndex !== -1) {
      // 如果存在相同商品和SKU，更新数量
      cartData[existingIndex].quantity = parseInt(cartData[existingIndex].quantity) + parseInt(cartItem.quantity)
      console.log(`购物车缓存更新商品数量: 商品ID ${cartItem.productId}, SKU ID ${cartItem.skuId}, 新数量: ${cartData[existingIndex].quantity}`)
    } else {
      // 如果不存在，添加新项
      cartData.push({
        ...cartItem,
        productId: cartItem.productId,
        skuId: cartItem.skuId
      })
      console.log(`购物车缓存添加新商品: 商品ID ${cartItem.productId}, SKU ID ${cartItem.skuId}, 数量: ${cartItem.quantity}`)
    }
    
    this.setCartCache(userId, cartData)
  },

  /**
   * 从购物车缓存中移除商品
   * @param {string} userId 用户ID
   * @param {number} cartId 购物车项ID
   */
  removeFromCartCache(userId, cartId) {
    let cartData = this.getCartCache(userId)
    cartData = cartData.filter(item => item.cartId !== cartId)
    this.setCartCache(userId, cartData)
  },

  /**
   * 更新购物车缓存中的商品数量
   * @param {string} userId 用户ID
   * @param {number} cartId 购物车项ID
   * @param {number} quantity 新数量
   */
  updateCartItemQuantity(userId, cartId, quantity) {
    let cartData = this.getCartCache(userId)
    const itemIndex = cartData.findIndex(item => item.cartId === cartId)
    
    if (itemIndex !== -1) {
      if (quantity <= 0) {
        // 如果数量为0或负数，移除该项
        cartData.splice(itemIndex, 1)
      } else {
        cartData[itemIndex].quantity = quantity
      }
      this.setCartCache(userId, cartData)
    }
  }
}